<?php

namespace App\Http\Controllers\Admin\Examine;

use App\Http\Controllers\Controller;
use App\Models\examine\ConfigModel;
use App\Models\examine\RecordDetailModel;
use App\Models\examine\RecordModel;
use App\Models\examine\ReimburseModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Detail extends Controller
{

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $auth = $request->get('auth');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $examine_no = $request->input('examine_no', '');
        $status = $request->input('status', '');
        $is_urge = $request->input('is_urge', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $record_where = [
            'type' => 1,
        ];
        if ($examine_no) {
            $record_where['examine_no'] = $examine_no;
        }
        if ($is_urge) {
            $record_where['is_urge'] = $is_urge;
        }

        $query = RecordDetailModel::query()->with('create_admin')->withWhereHas('record', function ($query) use ($record_where) {
            if ($record_where) {
                $query->where($record_where);
            }
        });

        if($status){
            $query = $query->where('status', $status);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();



        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'examine_no' => $item->record->examine_no ?? '',
                'type' => $item->type,
                'type_name' => ConfigModel::TYPE[$item->type] ?? '',
                'status' => $item->status,
                'status_text' => RecordDetailModel::STATUS[$item->status] ?? '',
                'submit_time' => $item->created_at->toDateTimeString(),
                'submit_user' => $item->create_admin ? $item->create_admin->staff->name: '',
                'examine_time' => $item->examine_time ?? '',
                'is_urge' => $item->record->is_urge ?? 0,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }



    /**
     * Notes:审核通过
     * User: xiangzi
     * Date: 2024/9/14
     * Time: 17:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function pass($id){
        $model = RecordDetailModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $record = RecordModel::find($model->record_id);
        if(!$record){
            return $this->error('数据不存在');
        }
        DB::beginTransaction();
        try {
            $model->status = 2;
            $model->examine_time = date('Y-m-d H:i:s');
            $model->save();

            switch ($record->examine_type) {
                case 1:
                    $find_next = RecordDetailModel::where('record_id', $model->record_id)->where('is_examine', 0)->orderBy('sort')->first();
                    if($find_next){
                        $find_next->is_examine = 1;
                        $find_next->save();
                    }else{
                        $record->status = 2;
                        $record->save();
                    }
                    break;
                case 2:
                    $record->status = 2;
                    $record->save();
                    break;
                case 3:
                    $find_else = RecordDetailModel::where('record_id', $model->record_id)->where('status', 1)->first();
                    if(!$find_else){
                        $record->status = 2;
                        $record->save();
                    }
                    break;
                default:

            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:不通过
     * User: xiangzi
     * Date: 2024/9/18
     * Time: 13:54
     * @return \Illuminate\Http\JsonResponse
     */
    public function refuse(Request $request, $id){
        $params = $request->all();
        $model = RecordDetailModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $record = RecordModel::find($model->record_id);
        if(!$record){
            return $this->error('数据不存在');
        }
        DB::beginTransaction();
        try {
            $model->status = 3;
            $model->examine_time = date('Y-m-d H:i:s');
            $model->examine_remarks = $params['reason'] ?? '';
            $model->save();

            $record->status = 3;
            $record->reason = $params['reason'] ?? '';
            $record->save();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    public function detail($id){
        $model = RecordDetailModel::find($id);
        if (!$model) {
            return $this->error('数据不存在');
        }

        $reimburse = ReimburseModel::where('examine_record_id', $model->record_id)->first();

        if (!$reimburse) {
            return $this->error('数据不存在');
        }

        return (new Reimburse())->detail($reimburse->id);

//        $return = [
//            'base_info' => [
//                'examine_type' => ConfigModel::EXAMINE_TYPE[$record->examine_type],
//                'submit_user' => $model->create_admin ? $model->create_admin->name : '',
//                'submit_time' => $model->created_at->toDateTimeString(),
//                'examine_no' => $record->examine_no,
//                'examine_status' => RecordModel::STATUS[$record->status],
//                'cancel_time' => $record->cancel_time,
//                'reason' => $record->reason
//            ],
//            'examine_info' => [
//                'amount' => $model->amount,
//                'use_to' => $model->use_to,
//                'file' => $model->file,
//                'remarks' => $model->remarks,
//            ],
//            'examine_process' => (new Record())->examine_info($model->record_id),
//            'copy_info' => (new Record())->copy_info($model->record_id)
//        ];
//
//        return $this->success($return);
    }


    public function export(Request $request)
    {
        $examine_no = $request->input('examine_no', '');
        $status = $request->input('status', '');
        $is_urge = $request->input('is_urge', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');


        $record_where = [
            'type' => 1,
        ];
        if ($examine_no) {
            $record_where['examine_no'] = $examine_no;
        }
        if ($is_urge) {
            $record_where['is_urge'] = $is_urge;
        }

        $query = RecordDetailModel::query()->with('create_admin')->withWhereHas('record', function ($query) use ($record_where) {
            if ($record_where) {
                $query->where($record_where);
            }
        });

        if($status){
            $query = $query->where('status', $status);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->orderBy('id', 'desc')
            ->get();



        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'examine_no' => $item->record->examine_no ?? '',
                'type' => $item->type,
                'type_name' => ConfigModel::TYPE[$item->type] ?? '',
                'status' => $item->status,
                'status_text' => RecordDetailModel::STATUS[$item->status] ?? '',
                'submit_time' => $item->created_at->toDateTimeString(),
                'submit_user' => $item->create_admin ? $item->create_admin->staff->name: '',
                'examine_time' => $item->examine_time ?? '',
                'is_urge' => $item->record->is_urge ?? 0,
            ];
            return $res;
        });

        $file_name = '问题件列表-'.date('Ymd').'.xlsx';
        return Excel::download(new ProblemExport($list), $file_name);

    }

}
